package com.campos.collection;

import android.location.Location;
import android.media.Image;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.campos.common.Config;
import com.campos.common.ContextData;
import com.campos.common.ImageData;
import com.campos.common.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class ProjectRW {

    public ProjectRW(){
        ContextData.instance = new ContextData();
    }
    public static ProjectRW instance;
    public void newpRroject(){
        Config.instance().newPorject();
        ContextData.instance.reset();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public int save(){
        if(ContextData.instance.imageList.size() < 1) return 1;
        this.saveImages();
        this.saveGPS();
        this.saveImageTimes();
        //this.saveIMU();
        this.saveCalibData();
        ContextData.instance.reset();
        return 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void saveGPS(){
        StringBuffer buffer = new StringBuffer();
        ContextData.instance.gpsDataList.forEach((gps) -> {
            double lon = gps.getLongitude();
            double lat = gps.getLatitude();
            double hei = gps.getAltitude();
            double acc = gps.getAccuracy();
            double gpst = gps.getTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            String gpstimestr = simpleDateFormat.format(gpst);

            String gpsinfo = String.format("%s,%f,%f,%f\n",gpstimestr,lon,lat,hei);
            buffer.append(gpsinfo);
        });
        String path = Config.instance().getCurrentProjPath_GPSInfo();
        Util.WriteTxtFile(buffer.toString(),path);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void saveIMU(){
        StringBuffer sb = new StringBuffer();
        String path = Config.instance().getCurrentProjPath_IMUInfo();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        ContextData.instance.imuDataList.forEach((sd)->{
            String timestr = simpleDateFormat.format(sd.date);
            String line = String.format("%s,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\n",
                    timestr,sd.date.getTime()/1000.0,
                    sd.angles[0],sd.angles[1],sd.angles[2],
                    sd.gyroscope[0],sd.gyroscope[1],sd.gyroscope[2],
                    sd.gravity[0],sd.gravity[1],sd.gravity[2],
                    sd.geomagnetic[0],sd.geomagnetic[1],sd.geomagnetic[2]
            );
            sb.append(line);
            if(sb.length() > 10000){
                Util.WriteTxtFile(sb.toString(),path);
                sb.setLength(0);
            }
        });
        Util.WriteTxtFile(sb.toString(),path);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void saveImageTimes(){
        StringBuffer sb = new StringBuffer();
        String path = Config.instance().getCurrentProjPath_ImageTimeStamp();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        ContextData.instance.imageTimeList.forEach((it)->{
            String timestr = simpleDateFormat.format(it) + "\n";
            sb.append(timestr);
        });
        Util.WriteTxtFile(sb.toString(),path);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void saveImages(){
        StringBuffer sb = new StringBuffer();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        AtomicInteger index = new AtomicInteger(1);
        ContextData.instance.imageList.forEach((img)->{
            String path = Config.instance().getCurrentImageFilePath(index.get());
            Util.CreateFileParentDir(path);
            saveImage(img,path);
            index.addAndGet(1);
        });
    }

    public void saveImage(ImageData img, String path){
        if(img.data.length <= 0) return;
        FileOutputStream output = null;
        try {
            File imgf = new File(path);
            output = new FileOutputStream(imgf);
            output.write(img.data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void  saveCalibData(){
        StringBuffer sb = new StringBuffer();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        for(int i = 0; i< ContextData.instance.imageList.size(); i++) {
            ImageData imd =  ContextData.instance.imageList.get(i);
            Date time = imd.date;
            double lon = -1;
            double lat = -1;
            double hei = -1;
            Location loc = imd.pos;
            if(loc != null){
                lon = loc.getLongitude();
                lat = loc.getLatitude();
                hei = loc.getAltitude();
            }

            String timestr = simpleDateFormat.format(time);
            String line = String.format("%04d,%s,%f,%f,%f,%f,%f,%f\n",
                    i,timestr,lon,lat,hei,imd.heading,imd.pitch,imd.roll
            );
            sb.append(line);
        }
        String path = Config.instance().getCurrentProjPath_IMUCalibInfo();
        Util.WriteTxtFile(sb.toString(),path);
    }
}
